<!--
 * @Description:我的购物车
 * @version: v1.0
 * @Author: Wang Xi
 * @Date: 2023-5-18 14:10:00
 * @LastEditors: Yejing
 * @LastEditTime: 2023-06-20 14:35:43
-->
<template>

	<view class="my-cart-container">
		<c-layout>
			<c-navigation-bar slot="head" :bgColor="true" :title="$t('home.MyCat')">
			</c-navigation-bar>
			<view class="" style="margin: 0 40rpx 40rpx;">

				<u-notice-bar type="" mode="horizontal" color="rgba(41, 52, 208, 1)" border-radius="8"
					bgColor="rgba(41, 52, 208, 0.1)" :list="list" :more-icon="true" @getMore="goActice()"></u-notice-bar>
			</view>
			<view class="" v-if="cartList">
				<view class="more-box"
					style="display: flex;margin: 0 40rpx; justify-content: space-between;align-items: center;">

					<view class="" style="display: flex;">
						<u-checkbox @change="CheckAll" :value="check" shape="circle">
							{{$t('storeManagement.CheckAll')}}
						</u-checkbox>


					</view>

					<view class="colletBtn" @click="collectGoodsAjax()">
						{{$t('storeOfInterest.collet')}}
					</view>

				</view>
				<view class="" style=" text-align: center;color: #ccc;">
					{{$t('system.rightdelete')}}
				</view>
			</view>

			<u-empty v-else :text="$t('home.catTips')" icon-size="159" mode="car" margin-top="64" ></u-empty>

			<view class="container-box">
				<!-- 				<u-swipe-action :btnWidth="90" :show="item.show" v-for="(item,index) in cartList" :index="index"
					:key="item.skuId" @click="deleteClick(item,index)" :options="options" @open="open">
					<view class="item u-border-bottom" style="display: flex;"> -->
				<!-- 此层wrap在此为必写的，否则可能会出现标题定位错误 -->
				<!-- <view class="title-wrap"> -->
				<!-- <shopCart :key="item.shopId" radius="26rpx" :checkList="checkList" 
								@checkChange="cartCheckChange" @numChange="numChange(arguments,item)" :data="item"
								:show-shop="true">
							</shopCart> -->
				<!-- 	</view>
					</view>
				</u-swipe-action> -->

				<shopCart radius="26rpx" :checkList="checkList" v-for="(item,index) in cartList" :key="item.shopId"
					@checkChange="cartCheckChange" @numChange="numChange(arguments,item)" :data="item"
					@deleteClick="deleteClick(arguments,index)" :show-shop="true">
				</shopCart>


				<view class="goods-box">
					<view class="title">
						{{$t('product.recommendCommodities') }}

					</view>
					<view class="reviews-main">
						<productCard :details="{...item,h:280}" v-for="item in goodList" :key="item.id"
							@click="goProductDetail(item)">
						</productCard>
					</view>
				</view>

			</view>

			<notTabbar slot="footer">
				<view class="footer-handle">
					<view class="total-price">
						<p class="total">{{$t('home.total')}} ({{ checkList.length }} {{$t('home.item')}}) :</p>
						<p class="price">${{ totalPrice }}</p>
					</view>
					<u-button :loading="isloading" @click="submitOrder" class="blue">{{$t('home.ProceedToCheckout')}}</u-button>
				</view>
			</notTabbar>
		</c-layout>
		<!--        弹框-->
		<promptDialog ref="promptDialogs_cart"></promptDialog>
	</view>
</template>

<script>
	import {
		math
	} from '@/common/math.js'
	export default {
		data() {
			return {
				isloading: false,
				// 购物车列表
				list: [123213212312321312321321],
				goodList: [],
				cartList: null,
				checkList: [],
				disabled: false,
				btnWidth: 90,
				show: false,
				check: false,
				isactivity: false,

			};
		},
		onLoad() {
			//获取推荐
			this.$u.get(`/app/shopGoodsInfo/productRecommended`).then((res) => {
				console.log("获取推荐", res)
				this.goodList = res.data

			}, )
			// 获取活动
			this.$u.post('/app/seckillActivity/oneActivity', {
				activityLocaltion: 1
			}).then(res => {
				console.log("购物车列表", res)
				this.isactivity = res.data ? true : false
				this.list = [res.data ? res.data.activityName : this.$t('home.catError')]
			}, )

		},
		// onReady() {
		// 	console.log('onshio');
		// 	// this.cartList=[]
		// 	this.$nextTick(() => {
		// 		this.getCartList()
		// 	})
		// },
		onShow() {
			console.log('onshow');
			this.cartList = []
			this.$nextTick(() => {
				this.getCartList()
			})
		},

		computed: {
			totalPrice() {
				if (!this.checkList.length) {
					return 0
				} else {
					let count = 0
					this.checkList.forEach(ele => {
						count = count + ele.price * ele.num
					});
					return count.toFixed(2)
				}
			},
		},
		watch: {
			checkList(newValue, oldValue) {
				console.log(newValue)
				if (newValue.length == 0) {
					this.check = false
				}
			},
			cartList(newValue, oldValue) {
				if(newValue && oldValue){
					if (oldValue && (newValue.length !== oldValue.length)) {
						this.checkList = []
					}
				}
				
			}
		},
		methods: {
			// 前往推荐商品详情
			goProductDetail(item) {
				uni.navigateTo({
					url: '/pages/productDetails/productDetails?productId=' + item.id
				});
			},
			// 前往活动详情
			goActice() {
				if (this.isactivity) {
					uni.navigateTo({
						url: '/pages/seckill/seckill'
					})
				} else {
					this.$u.toast(this.$t('home.catError'))
				}


			},

			// 获取购物车列表
			getCartList() {
				this.$u.get('/app/cart/list').then(res => {
					this.cartList = res.data
					// this.cartList.forEach(i=>{
					// 	i.show=false
					// })
					// console.log(7777,this.cartList);
				})
			},

			// 全选
			CheckAll() {
				this.check = !this.check
				console.log(this.cartList)
				let arr = []
				this.cartList.forEach(i => {
					i.shopCarts.forEach(j => {
						if (j.inventoryNum > 0) {
							arr = [...arr, ...[j]]
						}
					})


				})
				console.log(arr)
				this.checkList = this.check ? arr : []
			},
			//单选
			cartCheckChange(data) {
				// console.log(444,data);
				const { state, id, status } = data
				if ((status !== undefined) && !status) {
					this.$u.toast('该商品已经下架')
					return
				}
				if (state) {
					this.cartList.forEach(f => {
						let arr = f.shopCarts.find(x => x.skuId === id)
						if (arr) {
							this.checkList.push(arr)
							// console.log(555,this.checkList);
						}
					})
					// this.checkList.push(this.cartList.forEach(f => f.shopCarts.find(x=>x.skuId === id) ))
				} else {
					this.checkList = this.checkList.filter(f => f.skuId != id)
					// console.log(666,this.checkList);										
					// this.checkList = this.checkList.filter(f => f.skuId !== id)
				}
			},
			// 店铺id ， 商品id 收藏
			collectGoodsAjax() {
				if (!this.checkList.length) {
					this.$u.toast(this.$t('storeManagement.SelectProduct'))
					return
				}
				this.checkList.forEach(i => {
					this.$u.post('/app/shop/interestShopGoods/' + i.shopId + '/' + i.goodsId).then((res) => {
						this.$u.toast(this.$t('product.SuccessfulCollection'));
					});
				})

			},
			// 购物车数量增加
			numChange(data, item) {
				// console.log(222,data);
				let value = data[0]
				let index = data[1]

				// console.log(333,item.shopCarts[index].skuId);
				this.cartItemAdd(item.shopCarts[index].skuId, value, item.shopCarts[index].taskId).then(res => {
					data[2](res)
				})
			},
			// 购物车新增数量
			async cartItemAdd(skuId, num, taskId) {
				let status
				await this.$u.post('/app/cart/add', {
					num,
					skuId,
					taskId
				}).then(res => {
					status = true
				}).catch(err => {
					this.$u.toast(this.$t('system.outOf'))
					status = false
				})
				return status
			},

			// 删除
			deleteClick(data, index) {
				let id = data[0]
				let inx = data[1]
				this.getCartList()

			},
			//提交订单
			submitOrder() {
				this.order()
				// let that = this
				// this.$u.api.verifyIsSetPwdAjax(0).then(res => {
				// 	if (!res) {
				// 		this.$refs.promptDialogs_cart.show({
				// 			confirm: (close) => {
				// 				close()
				// 				this.$u.route('pages/modify/modify?type=1&set=0')
				// 			},
				// 			icon: 'errorTip',
				// 			btnColor: '#2934d0', //按钮颜色
				// 			btnTextType: 'Get a certificate', // 按钮文字
				// 			des: this.$t('product.PleaseSet'),
				// 			btnText: this.$t('product.GoToAdd'),
				// 		})


				// 		return false
				// 	} else {
				// 		if (!this.checkList.length) {
				// 			this.$u.toast(this.$t('storeManagement.SelectProduct'))
				// 			return
				// 		}
				// 		this.$u.post('/app/user/address/page', {
				// 			pageSize: 10000,
				// 			pageNum: 1
				// 		}).then(res => {
				// 			if (res.data.records.length == 0) {
				// 				this.$u.toast(this.$t('product.addressError'))
				// 			} else {
				// 				let obj = {}
				// 				obj = res.data.records[0]
				// 				let address = {}
				// 				res.data.records.forEach(i => {
				// 					if (i.defaultAddress) {
				// 						obj = i
				// 					}
				// 				})
				// 				obj.consigUser = obj.userName
				// 				obj.addressId = obj.id
				// 				this.$u.vuex('vuex_address_info', obj)
				// 				this.order(obj)
				// 			}

				// 		})
				// 	}
				// })



				// })
			},
			order() {
				if (!this.checkList.length) {
					this.$u.toast(this.$t('storeManagement.SelectProduct'))
					return
				}
				this.isloading = true

				console.log(999, this.checkList.map(m => m._id));
				// 生成订单
				this.$u.post('/app/shopOrderInfo/add', {
					cartIds: this.checkList.map(m => m._id),
					// ...obj
				}).then(res => {
					if (res.code == 200) {
						this.isloading = false
					}
					this.$u.vuex('vuex_shop_order_info', res.data)
					this.$u.vuex('vuex_shoping_cart', this.checkList) //选中商品
					this.$u.vuex('vuex_shoping_cartList', res.data)
					this.$u.route('/pages/orderDetails/orderDetails', {
						type: 'product',
						orderId: res.data.orderInfo.id,
						moneys: res.data.orderInfo.moneys,
						num: res.data.orderInfo.totalNum,
						totalPostage: res.data.orderInfo.totalPostage || 0
					})
				}).catch(e=>{
						this.isloading = false
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.my-cart-container {
		position: relative;
		font-family: PingFang SC;

		.colletBtn {
			padding: 5px 20px;
			background: #2934D0;
			font-size: 12px;
			color: #fff;
			border-radius: 10px;
		}

		.container-box {
			height: 72vh;
			overflow: auto;
			padding-bottom: 200rpx;

			/deep/ .u-swipe-action {
				margin-bottom: 30rpx;
				// border-radius: 28rpx;
				margin-right: 8rpx;
				overflow: hidden;

				.u-btn-text {
					&::after {
						content: "";
						display: block;
						width: 29rpx;
						height: 32rpx;
						background-image: url('@/static/svg/delete.svg');
						background-size: cover;
					}
				}
			}

			.u-btn-text {
				&::after {
					content: "";
					display: block;
					width: 29rpx;
					height: 32rpx;
					background-image: url('@/static/svg/delete.svg');
				}
			}
		}

		.item {
			display: flex;

			&::after {
				content: none;
			}

			.title-wrap {
				width: 100%;
			}
		}

		image {
			width: 120rpx;
			flex: 0 0 120rpx;
			height: 120rpx;
			margin-right: 20rpx;
			border-radius: 12rpx;
		}

		.title {
			text-align: left;
			font-size: 28rpx;
			color: $u-content-color;
			margin-top: 20rpx;
		}

		.cart-item-container {
			background-color: #fff;
			border-radius: 26rpx;
		}
	}

	/deep/ .u-empty {
		height: unset;
		margin-bottom: 64rpx;
	}

	/deep/ .u-swipe-content {
		flex: unset;
		width: 100%;
	}

	// 推荐列表
	.goods-box {
		.title {
			display: flex;
			justify-content: space-between;
			color: #000;
			font-size: 36rpx;
			font-weight: bold;
			line-height: 48rpx;
			margin: 0rpx 40rpx 32rpx;
		}

		.reviews-main {
			margin: 20px 20px 50px;
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;

			.product-card-container {
				width: 45%;
			}
		}

	}

	.cart-item-container {
		background-color: #fff;
		border-radius: 26rpx;
	}

	.footer-handle {
		display: flex;
		justify-content: space-between;
		height: 100%;
		align-items: center;

		.total-price {
			margin-left: 50rpx;

			.total {
				color: #91909A;
				font-size: 28rpx;
			}

			.price {
				color: #fff;
			}
		}

		>button {
			width: 380rpx;
			height: 100rpx;
			font-size: 32rpx;

			&:not(.button-hover[type="default"]) {
				color: #DEDEDE;
			}
		}
	}
</style>